<template>
    <Teleport to="#after-navigation" v-if="targetExists">
        <GradeManager />
    </Teleport>

    <div v-loading="loading">
        <h2 v-if="roleStore.isStudent">{{ $t('grade.report.user.tit') }}</h2>

        <div class="grade-navigation" v-if="courseId">
            <MoodleTabs :list="tabsList" active="2" v-if="roleStore.isStudent" />
            <MoodleTabs :list="tabsList1" active="3" v-else />
        </div>

        <div class="select-box" v-if="!roleStore.isStudent">
            <el-form-item :label="$t('grade.report.user.index.label')">
                <el-select v-model="selectedStudent" @change="handleSelectChange">
                    <el-option :label="$t('grade.report.user.index.option')" :value="0" />
                    <el-option v-for="user in memberList" :key="user.id" :label="user.name" :value="user.id" />
                </el-select>
            </el-form-item>
        </div>

        <template v-for="userGrade in userGradeList" :key="userGrade.student_id">
            <h3 v-if="!roleStore.isStudent">{{ $t('grade.report.user.index.tit_1') }} - {{ userGrade.student_name }}</h3>

            <!-- <h6 class="course-name">
                <el-icon size="16" color="#000"><Folder /></el-icon>
                {{ courseInfo?.name }}
            </h6> -->
            <el-table :data="userGrade.gradeList" stripe border class="custom-table">
                <el-table-column :label="courseInfo?.name">
                    <el-table-column :label="$t('grade.report.user.index.table_label_1')">
                        <template #default="{ row, $index }">
                            <div @click="goResourcePage(row)" class="item-name" :class="{ 'is-type': row.itemType !== 'total' }">
                                <el-icon size="16" color="#F06423" v-if="row.itemType === 'quiz'"><DocumentChecked /></el-icon>
                                <el-icon size="16" color="#06AAFF" v-else-if="row.itemType === 'video'"><VideoPlay /></el-icon>
                                <el-icon size="16" color="#616161" v-else-if="row.itemType === 'reflection'"><Memo /></el-icon>
                                <el-icon size="16" color="#999999" v-else-if="row.itemType === 'total'"><DataAnalysis /></el-icon>
                                <span>{{ row.itemName }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="grade" :label="$t('grade.report.user.index.table_label_2')" width="80">
                        <template #default="{ row }">{{ row.grade ? row.grade : '-' }}</template>
                    </el-table-column>
                    <el-table-column prop="range" :label="$t('grade.report.user.index.table_label_3')" width="80">
                        <template #default="{ row }">{{ row.range ? row.range : '-' }}</template>
                    </el-table-column>
                    <el-table-column prop="percentage" :label="$t('grade.report.user.index.table_label_4')" width="80">
                        <template #default="{ row }">{{ row.percentage ? row.percentage : '-' }}</template>
                    </el-table-column>
                    <el-table-column prop="contributiontocoursetotal" :label="$t('grade.report.user.index.table_label_5')" width="130">
                        <template #default="{ row }">{{ row.contributiontocoursetotal ? row.contributiontocoursetotal : '-' }}</template>
                    </el-table-column>
                </el-table-column>
            </el-table>
        </template>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'

import MoodleTabs from '@/components/MoodleTabs.vue'
import GradeManager from '@/components/GradeManager.vue'

import CourseService from '@/api/course'
import type { CourseItem, Grade, UserGrade } from '@/types/course'

import { useRoleStore } from '@/stores/role'
import { goPage } from '@/utils/global'

const route = useRoute()
const userStore = useUserStore()
const roleStore = useRoleStore()
const courseId = computed(() => Number(route.params.courseId))
const loading = ref(false)
const targetExists = ref(false)

const tabsList = ref([
    {
        value: '1',
        link: `/console/course/${courseId.value}/grade`,
        text: 'grade.report.user.index.tabs_1',
    },
    {
        value: '2',
        link: `/console/course/${courseId.value}/grade/user`,
        text: 'grade.report.user.index.tabs_2',
    },
])
const tabsList1 = ref([
    {
        value: '1',
        link: `/console/course/${courseId.value}/grade/rater`,
        text: 'grade.report.user.index.tabs_3',
    },
    {
        value: '3',
        link: `/console/course/${courseId.value}/grade/user`,
        text: 'grade.report.user.index.tabs_2',
    },
])

const courseInfo = ref<CourseItem>()
const userGradeList = ref<UserGrade[]>([])
const goResourcePage = (grade: Grade) => {
    switch (grade.itemType) {
        case 'quiz':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/quiz/${grade.id}`)
            break
        case 'video':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/videoTime/${grade.id}`)
            break
        case 'reflection':
            goPage(`/console/course/${courseId.value}/unit/${grade.unit_id}/assign/${grade.id}`)
            break
    }
}

function getCourseInfo() {
    CourseService.getById(courseId.value).then(res => {
        courseInfo.value = res
    })
}
function getGradeList() {
    loading.value = true
    if (!userStore.userinfoL) return

    if (roleStore.isStudent) {
        // 学生: 只能查自己的
        CourseService.gradeToStudent(courseId.value, userStore.userinfoL?.id)
            .then(res => {
                userGradeList.value = [res]
            })
            .finally(() => {
                loading.value = false
            })
    } else {
        // 非学生: 能查所有人
        CourseService.gradesToStudent(courseId.value)
            .then(res => {
                userGradeList.value = res
                memberList.value = userGradeList.value.map(item => {
                    return {
                        id: item.student_id,
                        name: item.student_name,
                    }
                })
            })
            .finally(() => {
                loading.value = false
            })
    }
}

// 成员列表
const selectedStudent = ref<number>(0)
const memberList = ref<{ id: number; name: string }[]>([])
const handleSelectChange = () => {
    if (selectedStudent.value === 0) {
        getGradeList()
    } else {
        loading.value = true
        CourseService.gradeToStudent(courseId.value, selectedStudent.value)
            .then(res => {
                userGradeList.value = [res]
            })
            .finally(() => {
                loading.value = false
            })
    }
}

function pageInit() {
    getCourseInfo()
    getGradeList()
    targetExists.value = !!document.querySelector('#after-navigation')
}
watch(
    () => userStore.userinfoL,
    () => {
        pageInit()
    },
)
watch(
    () => route.fullPath,
    () => {
        pageInit()
    },
)

onMounted(() => {
    pageInit()
})
</script>

<style lang="less">
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

h3 {
    margin-bottom: 18px;
    font-size: 26px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.grade-navigation {
    margin-bottom: 30px;
}

.select-box {
    display: flex;
    justify-content: flex-end;

    margin-bottom: 30px;

    .el-form-item {
        margin-bottom: 0;
    }

    .el-select {
        width: 200px;
    }
}

.course-name {
    margin-bottom: 15px;
    font-weight: bold;
    font-size: 14px;
    color: #000;
    display: flex;
    align-items: center;
    gap: 4px;
}

.el-table {
    margin-bottom: 30px;
}

.item-name {
    color: #000;

    display: flex;
    align-items: center;
    gap: 8px;

    &.is-type {
        cursor: pointer;
    }

    &:hover {
        color: #f06423;
    }
}
/* 修改表头背景色 */
.custom-table .el-table__header-wrapper th {
  background-color: #E5E5E5 !important; /* 浅蓝色背景，可按需调整 */
  color: #000 !important;
}

/* 隔行变色 */
.custom-table .el-table__body tr:nth-child(2n) td{
  background-color: #F2F2F2 !important; /* 浅灰色背景，可按需调整 */
}
</style>
